package cn.gson.crm.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.alibaba.fastjson.JSON;

import cn.gson.crm.model.dao.StudentPoDao;
import cn.gson.crm.model.entity.Attachs;

/**
 * 文件上传
 */
@WebServlet("/upload")
public class UploadSerlvet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private StudentPoDao stuPoDao = new StudentPoDao();
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//判断上传文件的请求类型
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		
		if(isMultipart){
			try {
			Attachs attach = new Attachs();
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			//创建一个上传文件器
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			//解析request
				List<FileItem> fileItems = upload.parseRequest(request);
				for (FileItem fileItem : fileItems) {
					//表单的名字
					String fieldName = fileItem.getFieldName();
					//表单的字段
					InputStream stream = fileItem.getInputStream();
					if(fileItem.isFormField()){
						//表示当前的表单item是一个普通的表单字段
						String value = Streams.asString(stream);
						System.out.println("表单名称：" + fieldName + ",表单值是：" + value);
						attach.setModel(value);
					}else{
						//表示这个item是一个文件字段
						//获取服务器的根目录
						String rootPath = request.getServletContext().getRealPath("/");
						//response.getWriter().write(rootPath);
						// 创建文件上传的根目录
						File uploadDir = new File(rootPath, "upload");
						// 判断上传目录是否存在，不存在就创建
						if(!uploadDir.exists()){
							uploadDir.mkdirs();
						}
						// 获取文件的原始名称xxxx.jpg
						String fileName = fileItem.getName();
						// 获取文件的后缀
						String suffix = fileName.substring(fileName.lastIndexOf("."));
						// 使用uuid生成新的文件名称
						String uuid = UUID.randomUUID().toString();
						System.out.println(uuid);
						File file = new File(uploadDir, uuid + suffix);
						// 将fileItem里面的inputStram写入file文件中。
						fileItem.write(file);
						
						attach.setFileName(fileName);
						attach.setFilePath("upload/" + uuid + suffix);
						attach.setFileSize(file.length());
					}
				}
				
				//存储附件信息
				Integer recordId = stuPoDao.saveAttach(attach);
				System.out.println(recordId);
				if(recordId != null){
					attach.setId(recordId);
					response.getWriter().append(JSON.toJSONString(attach));
				}else {
					response.getWriter().append("{\"message\":\"附件上传失败！\"}");
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}
